import requests
import PySimpleGUI as sg
requests.packages.urllib3.disable_warnings()
def translate_google(words):
    proxies={
    'http':'proxy.mgmt.intern:80',
    'https':'proxy.mgmt.intern:80'
    }
    url='https://translate.google.cn/_/TranslateWebserverUi/data/batchexecute?rpcids=MkEWBc&source-path=%2F&f.sid=-2649064291618077404&bl=boq_translate-webserver_20220330.08_p0&hl=zh-CN&soc-app=1&soc-platform=1&soc-device=1&_reqid=949393&rt=c'
    headers= {
        'authority': 'translate.google.cn',
        'accept': '*/*',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'origin': 'https://translate.google.cn',
        'referer': 'https://translate.google.cn/',
        'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': 'Windows',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',

        'x-same-domain': '1',
        
    }
    if is_contains_chinese(words):
        data={

    'f.req': f'[[["MkEWBc","[[\\"{words}\\",\\"auto\\",\\"en-US\\",true],[null]]",null,"generic"]]]'
           
            }

    else:
        data={

    'f.req': f'[[["MkEWBc","[[\\"{words}\\",\\"auto\\",\\"zh-CN\\",true],[null]]",null,"generic"]]]'
           
            }
    session=requests.Session()
    #x=session.post(url,headers=headers,data=data,proxies=proxies,verify=False)
    x=session.post(url,headers=headers,data=data,verify=False)
    print(x)
    #print('################')
    print(x.text)
    
    #print('***************')
    #print(re.findall(r',\[\[\\"(.*?)\\",\[\\',x.text))
    #for item in x.text.split('\\'):
    #    print("&",item)
    try:
        result=x.text.split('\\')[9][1:]
    except:
        result=''
    return result
def is_contains_chinese(strs):
    for _char in strs:
        if '\u4e00' <= _char <= '\u9fa5':
            return True
    return False
def translate_deepl(words):
    proxies={
    'http':'proxy.mgmt.intern:80',
    'https':'proxy.mgmt.intern:80'
    }
    url='https://www2.deepl.com/jsonrpc?method=LMT_handle_jobs'
    headers= {
        'Proxy-Connection': 'keep-alive',
        'authority': 'www2.deepl.com',
        'Accept': '*/*',
        'X-Requested-With': 'XMLHttpRequest',
        'origin': 'https://www.deepl.com',
        'content-type': 'application/json',
        'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',
        'Referer': 'https://www.deepl.com/',
        'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': "Windows",
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-site',
        
        
        
    }
    data={


"jsonrpc":"2.0",
"method": "LMT_handle_jobs",
"params":{"jobs":[{"kind":"default",
                   "sentences":[{"text":"hello，china","id":0,"prefix":""}],
                   "raw_en_context_before":[],"raw_en_context_after":[],
                   "preferred_num_beams":4,"quality":"fast"}],
          "lang":{"preference":{"weight":{"DE":0.24775,"EN":1.42681,"ES":0.21125,"FR":0.2158,"IT":0.18968,
                                          "JA":0.17776,"NL":0.11275,"PL":0.09224,"PT":0.07415,"RU":0.03347,"ZH":1.94436,"BG":0.02133,
                                          "CS":0.07605,"DA":0.09342,"EL":0.01556,"ET":0.07594,"FI":0.11492,"HU":0.05985,"LV":0.04869,
                                          "LT":0.0428,"RO":0.05598,"SK":0.06247,"SL":0.04421,"SV":0.08197},"default":"default"},
                  "source_lang_user_selected":"EN","target_lang":"ZH"},"priority":-1,"commonJobParams":{"browserType":1},"timestamp":1649032210082},"id":2670017

       
        }
    session=requests.Session()
    #x=session.post(url,headers=headers,data=data,proxies=proxies,verify=False)
    x=session.post(url,headers=headers,data=json.dumps(data),verify=False)
    print(x)
    false=False
    try:
        result=eval(a)['result']['translations'][0]['beams'][0]['sentences'][0]['text']
    except:
        result=''
    return result

def translate_sogou(words):
    proxies={
    'http':'proxy.mgmt.intern:80',
    'https':'proxy.mgmt.intern:80'
    }
    url='http://config.pinyin.sogou.com/api/app75/translate/getTranslate.php'
    headers= {
        'Proxy-Connection': 'keep-alive',
        'Accept': '*/*',
        'X-Requested-With': 'XMLHttpRequest',
        'origin': 'http://config.pinyin.sogou.com',
        'content-type': 'application/x-www-form-urlencoded',
        'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',
        'Referer': 'http://config.pinyin.sogou.com/api/app75/translate/index.html',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }
    data={


        'srclang':words,
        'lang_id':0,

       
        }
    session=requests.Session()
    #x=session.post(url,headers=headers,data=data,proxies=proxies,verify=False)
    x=session.post(url,headers=headers,data=data,verify=False)
    try:
        result=eval(x.text)['trans_result'][0]['dst']
    except:
        result=''
    return result
#translate('我爱你中国')
import pyperclip
#paste=pyperclip.paste()
#translate(paste)
pyperclip.copy("")
#layout = [[sg.Text('翻译机')]]Multiline
layout = [[sg.Text('欢迎使用翻译机，请复制你要翻译的句子或段落', key='-ML-', size=(70,0),font='Song')],
          [sg.Button('文本',),sg.Button('清空'),sg.Button('Exit')]]
win2_active = False
window = sg.Window("翻译机", layout,keep_on_top=True,location=(0,0),alpha_channel=.8, no_titlebar=True,grab_anywhere=True)
before=''
while True:

    #这里定义了刷新频率 单位是毫秒    
    event, values = window.read(timeout=500)
    
    paste=pyperclip.paste()
    if event == sg.WIN_CLOSED or event == 'Exit': # if user closes window or clicks cancel
        break
    if event == '文本':
        #print('111111111111111')
        if 'win2' in dir():
            win2.close()
        win2_active = True
        if  'res' in dir():
            pass
        else:
            res="请先复制要翻译的内容"
        layout2 = [[sg.Multiline(res,key='-ML-', size=(80,6),font='Song'),],]
        win2 = sg.Window('翻译机文本', layout2)
    if event == '清空':
        window['-ML-'].update('')
    if win2_active:
        ev2, vals2 = win2.read(timeout=100)
        if ev2 == sg.WIN_CLOSED or ev2 == 'Exit':
            win2_active  = False
            win2.close()




    
    if paste==before:
        continue
    else:
        res=translate_sogou(paste)
        #sg.popup_scrolled(res,auto_close = True,auto_close_duration = 4)
        #sg.popup(res,auto_close = True,auto_close_duration = 4)
        window['-ML-'].update(res)
        
        print('hello')
        print(res)
        pass
        #
    before=paste
    #res=translate(res)

    


    



window.close()

